﻿using CommunityToolkit.Mvvm.Input;
using System.Threading;
using System.Threading.Tasks;
using UpperComputer.WPF.Entry.Common.Extensions;
using YFurion.Application;

namespace UpperComputer.WPF.Entry.Common
{
    public class ManagementViewModel : BaseViewModel
    {
        /// <summary>
        /// 当前第一页
        /// </summary>
        public int CurrentFirst { get; } = 1;

        private int _current = 1;
        /// <summary>
        /// 当前页
        /// </summary>
        public virtual int Current
        {
            get => _current;
            set => SetProperty(ref _current, value);
        }

        public IAsyncRelayCommand<string> OperationCommand { get; }

        public ManagementViewModel()
        {
            OperationCommand = new AsyncRelayCommand<string>(OperationCommand_Execute, OperationCommand_CanExecute);
        }

        protected void SetCurrent(object current)
        {
            if (current != null)
            {
                Current = (int)current;
            }
        }

        protected void SetSkipCount(PagedResultRequestDto query)
        {
            query.SkipCount = (Current - 1) * query.MaxResultCount;
        }

        protected override void CancelToken(object parameter)
        {
            base.CancelToken(parameter);
            OperationCommand.CancelToken();
        }

        private bool OperationCommand_CanExecute(object parameter)
        {
            return CanOperation(parameter);
        }

        protected virtual bool CanOperation(object parameter)
        {
            return !OperationCommand.IsRunning;
        }

        public Task OperationCommand_Execute(string operation, CancellationToken cancellationToken)
        {
            Task task;
            switch (operation)
            {
                case Constant.OPERATION_POST:
                    task = PostAsync(cancellationToken);
                    break;
                case Constant.OPERATION_PUT:
                    task = PutAsync(cancellationToken);
                    break;
                case Constant.OPERATION_DELETE:
                    task = DeleteAsync(cancellationToken);
                    break;
                default:
                    task = OperationAsync(operation, cancellationToken);
                    break;
            }

            return task;
        }

        protected virtual Task PostAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        protected virtual Task PutAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        protected virtual Task DeleteAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        protected virtual Task OperationAsync(string operation, CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
